package mo.golden;

import mo.common.ListNode;

public class L02_07 {

    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) {
            return null;
        }
        ListNode tmp = headA;
        int lenA = 0;
        while (tmp != null) {
            lenA++;
            tmp = tmp.next;
        }
        tmp = headB;
        int lenB = 0;
        while (tmp != null) {
            lenB++;
            tmp = tmp.next;
        }
        while (lenA < lenB) {
            headB = headB.next;
            lenB--;
        }
        while (lenB < lenA) {
            headA = headA.next;
            lenA--;
        }
        while (headA != null && headB != null) {
            if (headA == headB) {
                return headA;
            }
            headA = headA.next;
            headB = headB.next;
        }
        return null;
    }

}
